package com.jhinwins.equipmenteb.equipmentebserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jhinwins.equipmenteb.equipmentebserver.service.OrderService;
import com.jhinwins.equipmenteb.equipmentebserver.utils.RespUtils;
import com.jhinwins.equipmenteb.equipmentebserver.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("order")
public class OrderController {
    private OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 获取订单
     */
    @GetMapping
    public JSONObject getOrders(@RequestParam String orderState) {
        // TODO: 2018/3/27 用户id应该用shiro获取
        if (UserUtils.curUser == null) {
            return RespUtils.createResp(RespUtils.UN_LOGIN);
        }
        return RespUtils.createSucResp(orderService.getOrders(UserUtils.curUser.getId(), orderState));
    }

    /**
     * 结算
     */
    @PostMapping("settlement")
    public JSONObject settlement(@RequestBody String data) {
        JSONObject params = JSON.parseObject(data);
        List<Long> orderids = params.getJSONArray("orderids").toJavaList(Long.class);
        String addr = params.getString("addr");

        return RespUtils.createSucResp(orderService.settlementByIds(orderids, addr));
    }

    /**
     * 发起归还请求
     */
    @PostMapping("reqrevert")
    public JSONObject reqRevert(@RequestBody String data) {
        JSONObject params = JSON.parseObject(data);
        Long orderid = params.getLong("orderid");
        return RespUtils.createSucResp(orderService.reqRevert(orderid));
    }

    /**
     * 确认归还
     */
    @PostMapping("confirmrevert")
    public JSONObject confirmRevert(@RequestBody String data) {
        JSONObject params = JSON.parseObject(data);
        Long orderid = params.getLong("orderid");
        return RespUtils.createSucResp(orderService.confirmRevert(orderid));
    }
}
